using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.Diagnostics;

namespace Spike.ContractBuilder
{
    public class DynamicServiceHost : ServiceHost
    {
        private string _fileName;

        public string FileName
        {
            get { return _fileName; }
            set 
            { 
                _fileName = value;
                ApplyConfiguration();
            }
        }

        private string _serviceName;

        public string ServiceName
        {
            get { return _serviceName; }
            set { _serviceName = value; }
        }
	
        public DynamicServiceHost(string serviceName, Type serviceType, string filename)
        {
            _serviceName = serviceName;
            _fileName = filename;

            this.InitializeDescription(serviceType, new UriSchemeKeyedCollection());

        }

        protected override void ApplyConfiguration()
        {
            ExeConfigurationFileMap filemap = new System.Configuration.ExeConfigurationFileMap();
            filemap.ExeConfigFilename = _fileName;

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);

            bool loaded = false;

            foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)
            {
                if (!loaded)
                    if (se.Name == ServiceName)
                    {
                        base.LoadConfigurationSection(se);
                        loaded = true;
                    }
            }

            if (!loaded)
                throw new ArgumentException("ServiceElement doesn't exist");
        }        
}

}
